package nl.windgazer.arachne.components.yql;

import nl.windgazer.arachne.services.yql.YQLConduit;

import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;

public class YQLFlickrPhotoset extends YQLFlickrPhotos {

	//Injects and Persists

	@Inject
	private YQLConduit yc;

	//Properties and Parameters

	@Parameter(required=true)
	private String user;

	@Parameter(required=true)
	private String title;

	private JSONObject[] photos = null;

	private JSONObject photoq;

	private JSONObject infoq;

	//Components
	//Events
	//Other (check for business-logic, it should not remain here)

	@Override
	public JSONObject[] getPhotos() {
		if (photos==null) {
			photoq = yc.jsonByAlias("windgazer", "flickrsetphotos", "user", user, "title", title);
			final int count = photoq.getInt("count");
			if (count==0) {
				return null;
			}
			infoq = yc.jsonByAlias("windgazer", "flickrsetpages", "user", user, "title", title);
			final JSONArray pa = photoq.getJSONObject("results").getJSONArray("photo");
			photos = new JSONObject[pa.length()];
			for (int i = 0; i < pa.length(); i++) {
				final JSONObject photo = pa.getJSONObject(i);
				final JSONObject info = getById(infoq, photo.getString("id"));
				if (info!=null) photo.put("photopage", info.getJSONObject("urls").getJSONObject("url").get("content"));
				photos[i] = photo;
			}
		}
		return photos;
	}

}
